<template>
  <div class="content-area" >
    <el-container class="container-style">

      <el-container>
        <div style="width: 96%; margin: 0 auto; display: flex; flex-direction: column; align-items: center;">
          <div style="display: flex; align-items: center;">
            <div>
              <h2>投诉与建议管理</h2>
            </div>

            <el-select
                v-model="value"
                placeholder="选择某一小区"
                size="large"
                style="width: 240px; margin-left: 10px;"
                @change="handleSelectChange"
            >
              <el-option
                  v-for="item in communityList"
                  :key="item.id"
                  :label="item.communityName"
                  :value="item.id"
              />
            </el-select>

            <el-button
                type="primary"
                size="large"
                style="margin-left: 10px;"
                @click="clearSelection"
            >
              清空选择
            </el-button>
          </div>

          <div style="background-color: white; padding: 20px; margin-top: 10px; width: 100%">
          <div>
            <div class = table-header-container>
            <div class="search-container">
              <el-select v-model="searchOption" placeholder="请选择查询方式" class="search-select">
                <el-option label="按业主id查询" value="ownerId"></el-option>
                <el-option label="按处理状态查询" value="status"></el-option>
              </el-select>

              <el-input v-model="searchQuery" :placeholder="
                  searchOption === 'status'? '待处理，处理中，已完成' :
                  '请输入查询关键词'
                " class="search-input"></el-input>
              <el-button type="primary" @click="searchComplain" class="search-button">查询</el-button>
            </div>
            </div>
            <!-- 使用 v-if 判断是否展示表格 -->
            <div v-if="complaintSuggestionPage && complaintSuggestionPage.data && complaintSuggestionPage.data.records.length > 0">
              <table style="text-align: center; width: 100%; border-collapse: collapse;"> <!-- 添加 text-align: center; 使表格内容居中 -->
                <thead>
                <tr>
                  <th style="width: 80px; height: 50px; border: 1px solid #eee;">数据id</th>
                  <th style="width: 80px; height: 50px; border: 1px solid #eee;">类型</th>
                  <th style="width: 80px; height: 50px; border: 1px solid #eee;">业主id</th>
                  <th style="width: 120px; height: 50px; border: 1px solid #eee;">内容</th>
                  <th style="width: 120px; height: 50px; border: 1px solid #eee;">附件</th>
                  <th style="width: 80px; height: 50px; border: 1px solid #eee;">状态</th>
                  <th style="width: 120px; height: 50px; border: 1px solid #eee;">措施</th>
                  <th style="width: 80px; height: 50px; border: 1px solid #eee;">处理人员id</th>
                  <th style="width: 80px; height: 50px; border: 1px solid #eee;">完成时间</th>
                  <th style="width: 80px; height: 50px; border: 1px solid #eee;">操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(item, index) in complaintSuggestionPage.data.records" :key="index">
                  <td>{{ item.id }}</td>
                  <td>{{ item.type }}</td>
                  <td>{{ item.ownerId }}</td>
                  <td>{{ item.complainContent }}</td>
                  <td><el-button v-if="item.attachment" type="text" @click="downloadFile(item.attachment)">下载附件</el-button>
                  <span v-else>无</span></td>
                  <td>{{ item.processingStatus }}</td>
                  <td>{{ item.measure }}</td>
                  <td>{{ item.handlerId }}</td>
                  <td>{{ item.completionDate }}</td>
                  <td>
                    <el-button type="success" @click="toggleStatus(item)">更新状态</el-button>
                  </td>
                </tr>
                </tbody>
              </table>
            </div>
            <!-- 使用 v-else-if 判断是否展示错误信息 -->
            <div v-else-if="errorMessage">{{ errorMessage }}</div>
            <!-- 如果没有数据也没有错误信息，展示提示信息 -->
            <div v-else>暂无投诉与建议记录</div>
          </div>
            <div style="display: flex; justify-content: center; width: 100%;">
              <el-pagination
                  class="footer"
                  v-if="complaintSuggestionPage && complaintSuggestionPage.data"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="[6, 8, 10]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="complaintSuggestionPage.data.total"
              >
              </el-pagination>
            </div>
          </div>
        </div>

      </el-container>

    </el-container>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';

export default {
  data() {
    return {
      userName: localStorage.getItem('adminName') || '',
      complaintSuggestionStats: [],
      complaintSuggestionPage: null,
      errorMessage: '',
      currentPage: 1,
      pageSize: 10,
      newComplaint: {},
      showDialog: false,
      communityId:"" ,
      unprocessedCount: 0,
      processedCount: 0,
      processingCount: 0,
      searchQuery: '',
      searchOption: '',
      value: null,
      communityList: null
    };
  },
  setup() {
    const router = useRouter();
    return {
      router
    };
  },
  methods: {
    clearSelection() {
      // 清空选择
      this.value = null;
      this.communityId = "";
      // 重新加载默认数据
      this.fetchComplaintSuggestionPage();
    },
    handleSelectChange(value) {
      this.communityId = value;
      this.fetchComplaintSuggestionPage();
    },
    async fetchCommunityList() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未获取到token，请重新登录');
          return;
        }
        const response = await axios.get('/api/community/search', {
          headers: {
            Authorization: token
          }
        });
        console.log(response)
        this.communityList = response.data.data;
        console.log('this.community',this.communityList)
      } catch (error) {
        ElMessage.error('获取小区列表时出错：' + error.message);
      }
    },
    backAdminHome(url) {
      this.$router.push(url);
    },
    async fetchComplaintSuggestionPage() {
      try {
        const token = localStorage.getItem('token');
        let url = '/api/complain';
        let params = {
          current: this.currentPage,
          size: this.pageSize,
          communityId: this.communityId
        };
        if (this.searchOption === 'ownerId') {
          params.ownerId = this.searchQuery;
        }else if (this.searchOption === 'status'){
          params.status = this.searchQuery;
        }
        const response = await axios.get(url, {
          headers: {
            Authorization: token
          },
          params: params
        });
        if(response.data.code===200) {
          this.complaintSuggestionPage = response.data;
        }else{
          ElMessage.error('获取投诉建议信息失败，请输入正确信息')
        }
        if (this.complaintSuggestionPage.data && this.complaintSuggestionPage.data.records) {
          // 先按状态排序：待处理、处理中、已完成
          const statusOrder = {
            '待处理': 0,
            '处理中': 1,
            '已完成': 2
          };
          this.complaintSuggestionPage.data.records.sort((a, b) => {
            const statusA = statusOrder[a.processingStatus];
            const statusB = statusOrder[b.processingStatus];
            if (statusA!== statusB) {
              return statusA - statusB;
            }
            // 同一状态下按id正序排序
            return a.id - b.id;
          });
          this.complaintSuggestionPage.data.records.forEach((group, index) => {
            if (index > 0 && group.processingStatus === this.complaintSuggestionPage.data.records[index - 1].processingStatus) {
              group.sort((a, b) => {
                const dateA = new Date(a.completionDate);
                const dateB = new Date(b.completionDate);
                return dateB - dateA;
              });
            }
          });
        }
      } catch (error) {
        ElMessage.error('获取投诉与建议记录失败:', error);
        this.errorMessage = '获取数据失败，请稍后重试';
      }
    },
    async searchComplain() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未授权，请先登录');
          return;
        }
        if (this.searchOption === 'ownerId') {
          const response = await axios.get('/api/complain', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.communityId,
              ownerId: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.complaintSuggestionPage = response.data;
          } else {
            ElMessage.error('查询投诉建议信息失败，请输入正确信息');
          }
        } else if (this.searchOption === 'status') {
          const response = await axios.get('/api/complain', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.communityId,
              status: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.complaintSuggestionPage = response.data;
          } else {
            ElMessage.error('查询投诉建议信息失败，请输入正确信息');
          }
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    },
    async downloadFile(path) {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('/api/file', {
          params: {
            path: path
          },
          headers: {
            Authorization: token
          },
          responseType: 'blob'
        });
        const blob = new Blob([response.data], { type: response.headers['content-type'] });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        const contentDisposition = response.headers['content-disposition'];
        const fileName = contentDisposition ? contentDisposition.split('filename*=UTF-8\'\'')[1] : 'downloaded_file';
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
        ElMessage.success('文件下载成功');
      } catch (error) {
        ElMessage.error('文件下载失败：' + error.message);
      }
    },

    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.fetchComplaintSuggestionPage();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchComplaintSuggestionPage();
    },
    async toggleStatus(item) {
      const statusOrder = ['处理中', '待处理', '已完成'];
      const currentIndex = statusOrder.indexOf(item.processingStatus);
      const newStatus = statusOrder[(currentIndex + 1) % statusOrder.length];
      const token = localStorage.getItem('token');
      try {
        const response = await axios.put(`/api/complain/${item.id}/status`, null, {
          headers: {
            Authorization: token
          },
          params: {
            status: newStatus,
            handlerId: item.handlerId,
            completionDate: item.completionDate
          }
        });
        if (response.status === 200) {
          item.processingStatus = newStatus;
          ElMessage.success('处理状态更新成功');
        } else {
          ElMessage.error('处理状态更新失败');
        }
        this.fetchComplaintSuggestionPage();
      } catch (error) {
        ElMessage.error('处理状态更新失败，请稍后重试');
      }
    }
  },
  mounted() {
    this.fetchComplaintSuggestionPage();
    this.fetchCommunityList();
  }
};
</script>

<style scoped>

.footer {
  margin-top: 20px;
  text-align: center;
  padding: 10px;
  transition: margin-left 0.3s;
}

table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  border: 1px solid #eee;
  padding: 8px;
}

.container-style {
  height: 100%;
}

.header-style {
  background-color: rgb(204, 225, 234);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.footer-style {
  text-align: center;
  background-color: rgba(129, 175, 184, 0.83);
}



.menu-header {
  padding: 0;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.search-input {
  flex: 1;
  width: 350px;
  margin-right: 10px;
}

.search-select {
  flex: 1;
  width: 30px;
}

.search-button {
  min-width: 80px;
}

.table-header-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}
.content-area {
  background-color: #f2f5fa;
  padding: 20px;
  height: calc(100vh - 120px); /* 50(header) + 10(footer padding top) + 60(footer height & bottom margin) */
  overflow-y: auto; /* 启用滚动条 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}

.community-select-wrapper {
  display: flex;
  align-items: center;
}
</style>